// [Ref] http://www.cnblogs.com/rubylouvre/archive/2011/11/28/2264717.html

var fs = require('fs');

var rmdirSync = (function() {

    function iterator(url, dirs) {
        var stat = fs.statSync(url);
        if (stat.isDirectory()) {
            dirs.unshift(url);
            inner(url,dirs);
        } else if (stat.isFile()) {
            fs.unlinkSync(url);
        }
    }

    function inner(path, dirs) {
        var arr = fs.readdirSync(path);
        for (var i = 0, el; el = arr[i++]; ) {
            iterator(path+'/'+el, dirs);
        }
    }

    return function(dir, cb) {
        cb = cb || function(){};
        var dirs = [];

        try {
            iterator(dir, dirs);
            for (var i = 0, el; el = dir[i++]; ) {
                console.log(el);
                fs.rmdirSync(el);
            }
            cb();
        } catch(e) {
            e.code === 'ENOENT' ? cb() : cb(e);
        }
    }
})();

module.exports = rmdirSync;